package com.prawn.information.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.prawn.information.pojo.Experts;
import com.prawn.information.pojo.Post;
import com.prawn.information.service.ExpertsService;
import com.prawn.information.service.PostService;
import com.prawn.information.util.FastDFSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import com.prawn.information.pojo.Details;
import com.prawn.information.service.DetailsService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;

/**
 * 控制器层
 *
 * @author Administrator
 */
@RestController
@CrossOrigin
@RequestMapping("/details")
@Api(value = "回帖接口", tags = "回帖接口")
public class DetailsController {

    @Autowired
    private DetailsService detailsService;

    @Autowired
    private ExpertsService expertsService;

    @Autowired
    private PostService postService;

    @Autowired
    private FastDFSUtil fastDFSUtil;

    @Value("${fdfs.web-server-url}")
    private String fastdfsUrl;

    /**
     * 查询全部回帖-分页
     *
     * @return
     */
    @ApiOperation(value = "查询全部回帖-分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", paramType = "path", required = true),
            @ApiImplicitParam(name = "size", value = "每页数据数量", paramType = "path", required = true)
    })
    @RequestMapping(value = "/findAll/{page}/{size}", method = RequestMethod.GET)
    public Result findAll(@PathVariable int page, @PathVariable int size) {
        Page<Details> pageList = detailsService.findAll(1, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Details>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据ID查询回复
     *
     * @param id ID
     * @return
     */
    @ApiOperation(value = "根据ID查询回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "回帖id", paramType = "path", dataType = "String", required = true)
    })
    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查询成功", detailsService.findById(id));
    }

    /**
     * 根据帖子ID查询回复
     *
     * @param postId ID
     * @return
     */
    @ApiOperation(value = "根据帖子ID查询回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "postId", value = "帖子ID", paramType = "path", required = true),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "path", required = true),
            @ApiImplicitParam(name = "size", value = "每页数据数量", paramType = "path", required = true)
    })
    @RequestMapping(value = "/findByPost/{postId}/{page}/{size}", method = RequestMethod.GET)
    public Result findByPostId(@PathVariable String postId, @PathVariable int page, @PathVariable int size) {
        Page<Details> pageList = detailsService.findByPostId(postId, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Details>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据专家ID查询回复
     *
     * @param replier
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "根据专家ID查询回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "replier", value = "回复者", paramType = "path", required = true),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "path", required = true),
            @ApiImplicitParam(name = "size", value = "每页数据数量", paramType = "path", required = true)
    })
    @RequestMapping(value = "/findByReplier/{replier}/{page}/{size}", method = RequestMethod.GET)
    public Result findByReplier(@PathVariable String replier, @PathVariable int page, @PathVariable int size) {
        List<Integer> status = new ArrayList<>();
        status.add(0);
        status.add(1);
        status.add(2);
        Page<Details> pageList = detailsService.findByReplier(replier, status,  page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Details>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据用户ID查询回复
     *
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "根据用户ID查询回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", paramType = "path", required = true),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "path", required = true),
            @ApiImplicitParam(name = "size", value = "每页数据数量", paramType = "path", required = true)
    })
    @RequestMapping(value = "/findByUser/{userId}/{page}/{size}", method = RequestMethod.GET)
    public Result findByUser(@PathVariable String userId, @PathVariable int page, @PathVariable int size) {
        List<Integer> status = new ArrayList<>();
        status.add(0);
        status.add(1);
        status.add(2);
        Page<Details> pageList = detailsService.findByReplier(userId, status, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Details>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 回帖
     *
     * @param details
     */
    @ApiOperation(value = "回帖", notes = "权限：发帖人or专家 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "details", value = "回帖对象", dataType = "Details")
    })
    @RequestMapping(value = "/reply", method = RequestMethod.POST)
    public Result add(@RequestBody Details details) {
        details.setState(0); //待审核
        details.setPraiseNum(0);
        Iterable<Experts> expertsList = expertsService.findAll();
        for (Experts experts : expertsList) { // 回帖人是专家
            if (details.getReplier().equals(experts.getId())) {
                detailsService.add(details);
//                experts.setRepliesNum(experts.getRepliesNum() + 1); //专家回复数+1
//                expertsService.update(experts);
                return new Result(true, StatusCode.OK, "增加成功");
            }
        }
        Post post = postService.findById(details.getPostId()).get();
        if (details.getReplier().equals(post.getUserId())) { //回帖人是发帖人
            detailsService.add(details);
            return new Result(true, StatusCode.OK, "增加成功");
        }
        return new Result(false, StatusCode.ACCESSERROR, "权限不足");
    }

    /**
     * 管理员审核回帖通过
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "管理员审核回帖通过")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "回帖id", paramType = "path", dataType = "String", required = true)
    })
    @RequestMapping(value = "/agree/{id}", method = RequestMethod.PUT)
    public Result agree(@PathVariable String id) {
        Details details = detailsService.findById(0, id);
        if (details.isExperts() == true) {
            try {
                Experts experts = expertsService.findById(details.getReplier()); //查专家
//            List<Details> detailsList = detailsService.findByPostId(details.getPostId());
//            for (Details details1 : detailsList) {
//                if(details1.getReplier().equals(experts.getId())) {
//                    details.setState(1); //通过审核
//                    detailsService.update(details);
//                }
//            }
                String expertsId = postService.findById(details.getPostId()).get().getExpertsId();
                if(expertsId.equals(experts.getId())) { //如果该回复回复的是向该专家提问的帖子
                    int repliesNum = experts.getRepliesNum() + 1;  //专家回复量+1
                    experts.setRepliesNum(repliesNum);
                    expertsService.update(experts);
                }
//            return new Result(true, StatusCode.OK, "通过成功");
            } catch (Exception e){
                System.out.println("专家不存在");
                e.printStackTrace();
            }
        }
        details.setState(1); //通过审核
        detailsService.update(details);
        return new Result(true, StatusCode.OK, "通过成功");
    }

    /**
     * 管理员审核回帖不通过
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "管理员审核回帖不通过")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "回帖id", paramType = "path", dataType = "String", required = true)
    })
    @RequestMapping(value = "/refuse/{id}", method = RequestMethod.DELETE)
    public Result refuse(@PathVariable String id) {
        Details details = detailsService.findById(0, id);
        details.setState(2); //通过不审核
        detailsService.update(details);
        return new Result(true, StatusCode.OK, "拒绝成功");
    }

    /**
     * 回帖待审核列表
     *
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "回帖待审核列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", paramType = "path", required = true),
            @ApiImplicitParam(name = "size", value = "每页数据数量", paramType = "path", required = true)
    })
    @RequestMapping(value = "/agreeing/{page}/{size}", method = RequestMethod.GET)
    public Result agreeing(@PathVariable int page, @PathVariable int size) {
        Page<Details> pageList = detailsService.findAll(0, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Details>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 回帖审核失败列表
     *
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "回帖审核失败列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", paramType = "path", required = true),
            @ApiImplicitParam(name = "size", value = "每页数据数量", paramType = "path", required = true)
    })
    @RequestMapping(value = "/failed/{page}/{size}", method = RequestMethod.GET)
    public Result failed(@PathVariable int page, @PathVariable int size) {
        Page<Details> pageList = detailsService.findAll(2, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Details>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 点赞回帖
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "点赞回帖")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "回帖id", dataType = "String", paramType = "path")
    })
    @RequestMapping(value = "/parise/{id}", method = RequestMethod.PUT)
    public Result parise(@PathVariable String id) {
        Details details = detailsService.findById(1, id);
        Integer praiseNum = details.getPraiseNum();
        details.setPraiseNum(praiseNum + 1);
        //专家点赞数+1
        if (details.isExperts() == true) {
            Experts experts = expertsService.findById(details.getReplier());
            experts.setPraiseNum(experts.getPraiseNum() + 1);
            expertsService.update(experts);
        }
        detailsService.update(details);
        return new Result(true, StatusCode.OK, "点赞成功");
    }

    /**
     * 删除回复
     *
     * @param id
     */
    @ApiOperation(value = "删除回复 - 使用绕过网关的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资讯id", dataType = "String", paramType = "path")
    })
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.PUT)
    public Result delete(@PathVariable String id) {
        Details details = detailsService.findById(id);
        details.setState(3);
        detailsService.update(details);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /**
     * 修改回复
     *
     * @param details
     */
    @ApiOperation(value = "修改回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "details", value = "回帖对象", dataType = "Details"),
            @ApiImplicitParam(name = "id", value = "回帖id", dataType = "String", paramType = "path")
    })
    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody Details details, @PathVariable String id) {
        details.setId(id);
        details.setState(0);
        details.setCreationTime(new Date());
        detailsService.update(details);
        return new Result(true, StatusCode.OK, "修改成功，请等待审核。");
    }

    /**
     * 查询删除历史
     *
     * @return
     */
    @ApiOperation(value = "查询删除历史")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", paramType = "path", required = true),
            @ApiImplicitParam(name = "size", value = "每页数据数量", paramType = "path", required = true)
    })
    @RequestMapping(value = "/findDelete/{page}/{size}", method = RequestMethod.GET)
    public Result findDelete(@PathVariable int page, @PathVariable int size) {
        Page<Details> pageList = detailsService.findAll(3, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Details>(pageList.getTotalElements(), pageList.getContent()));
    }

}
